package hdeloisd

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"hfhub/cache"
	"hfhub/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	wz := c.PostForm("wz")

	if title == "" || content == "" || wz == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.App{
		Title:   title,
		Content: content,
		Wz:      wz,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "redis_id" + strconv.Itoa(int(data.ID))
	var app models.App
	models.DB.Where("id=?", data.ID).First(&app)
	jsonAdd, _ := json.Marshal(app)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonAdd, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	offend := (page - 1) * size

	var count int64
	models.DB.Model(&models.App{}).Count(&count)

	var are []models.Are

	redis_key := "redis_list"
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Offset(offend).Limit(size).Find(&are)
		JsonLiat, _ := json.Marshal(are)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonLiat, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &are)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"are":   are,
		},
	})
	return
}

func Xq(c *gin.Context) {
	id := c.Query("id")
	var are models.Are

	redis_key := "redis_list"
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Where("id=?", id).First(&are)
		JsonLiat, _ := json.Marshal(are)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonLiat, time.Hour*2)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": are,
	})
}
